package com.liit.console.controller.front;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.liit.console.filter.WebContext;
import com.liit.module.entity.Files;
import com.liit.module.entity.Retail;
import com.liit.module.frame.utils.ConfigUtil;
import com.liit.module.frame.utils.Const;
import com.liit.module.frame.utils.FileUtil;
import com.liit.module.frame.utils.ValidatorUtils;
import com.liit.module.frame.utils.page.Pagination;
import com.liit.module.service.DictService;
import com.liit.module.service.FilesService;
import com.liit.module.service.RetailAreaService;
import com.liit.module.service.RetailService;

/**
 * @author dingweibo
 * @Title: RetailController.java
 * @Description: 授权门市
 * @date 2015年12月15日
 */
@Controller
@RequestMapping(value = "/retail")
public class RetailController {

	private Logger logger = Logger.getLogger(getClass());

	@Resource
	RetailService retailService;

	@Resource
	FilesService filesService;

	@Resource
	DictService dictService;

	@Resource
	RetailAreaService retailAreaService;

	/**
	 * 添加授权门市
	 * 
	 * @param retail
	 * @param pagination
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list")
	public String list(Retail retail, Pagination pagination) throws Exception {
		Map<String, Object> result = retailService.listPage(pagination, retail);
		List<Retail> list = (List<Retail>) result.get("list");
		BeanUtils.copyProperties(result.get("page"), pagination);
		Map<String, Map<String, Files>> imgMap = new HashMap<String, Map<String, Files>>();
		for (Retail r : list) {
			Map<String, Files> row = new HashMap<String, Files>();
			if (r.getImgOne() != null) {
				Files imgOnePath = filesService.selectById(r.getImgOne());
				imgOnePath.setPath(FileUtil.getUrl(imgOnePath));
				row.put("imgOne", imgOnePath);
			}
			if (r.getImgTwo() != null) {
				Files imgTwoPath = filesService.selectById(r.getImgTwo());
				imgTwoPath.setPath(FileUtil.getUrl(imgTwoPath));
				row.put("imgTwo", imgTwoPath);
			}
			if (r.getImgThree() != null) {
				Files imgThreePath = filesService.selectById(r.getImgThree());
				imgThreePath.setPath(FileUtil.getUrl(imgThreePath));
				row.put("imgThree", imgThreePath);
			}
			imgMap.put(r.getId().toString(), row);
		}
		WebContext.setAttribute("imgMap", imgMap);
		WebContext.setAttribute("list", list);
		WebContext.setAttribute(Const.PAGINATION, pagination);
		return "/front/retailList";
	}

	/**
	 * 添加授权门市
	 * 
	 * @return
	 */
	@RequestMapping(value = "/add")
	public String add(Integer id) {
		WebContext.setAttribute("retailRegion", dictService.selectByColumn(Const.RETAIL_REGION));
		if (id != null) {
			Retail retail = retailService.selectById(id);
			WebContext.setAttribute("retail", retail);
			WebContext.setAttribute("retailArea", retailAreaService.selectAreaByRegion(retail.getRegion(), Const.STATUS_ENABLED));
			if (retail.getImgOne() != null) {
				WebContext.setAttribute("imgOnePath", FileUtil.getUrl(filesService.selectById(retail.getImgOne())));
			}
			if (retail.getImgTwo() != null) {
				WebContext.setAttribute("imgTwoPath", FileUtil.getUrl(filesService.selectById(retail.getImgTwo())));
			}
			if (retail.getImgThree() != null) {
				WebContext.setAttribute("imgThreePath", FileUtil.getUrl(filesService.selectById(retail.getImgThree())));
			}
		} else {
			WebContext.setAttribute("retailArea", retailAreaService.selectAreaByRegion(0, Const.STATUS_ENABLED));
		}
		return "/front/retailAdd";
	}

	/**
	 * 保存授权门市
	 * 
	 * @param retail
	 * @param id
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@RequestMapping("/save")
	public String save(Retail retail, @RequestParam("imgOneFile") MultipartFile imgOneFile, @RequestParam("imgTwoFile") MultipartFile imgTwoFile,
			@RequestParam("imgThreeFile") MultipartFile imgThreeFile) {
		try {
			// 上传图片
			String path = ConfigUtil.get("file.upload.path") + Const.UPLOAD_PATH_RETAIL;
			String newFileName = null;
			int type = 0;
			String fileName = null;
			String ext = null;
			int size = 0;// 图片大小
			String contentType = null;
			Date now = new Date();
			Files filesRecord = null;
			// 图片1
			if (!imgOneFile.isEmpty()) {
				fileName = imgOneFile.getOriginalFilename();
				ext = fileName.substring(fileName.lastIndexOf('.') + 1);
				newFileName = UUID.randomUUID().toString() + "." + ext;
				size = (int) imgOneFile.getSize();
				contentType = imgOneFile.getContentType();
				File targetFile = new File(path, newFileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				imgOneFile.transferTo(targetFile);

				filesRecord = new Files();
				// 删除历史图片
				if (retail.getImgOne() != null) {
					filesRecord.setId(retail.getImgOne());
					filesRecord.setStatus(Const.FILES_STATUS_DELETE);
					filesService.updateById(filesRecord);
				}

				filesRecord.setPath(Const.UPLOAD_PATH_RETAIL + newFileName);
				filesRecord.setType(type);
				filesRecord.setName(fileName);
				filesRecord.setExt(ext);
				filesRecord.setSize(size);
				filesRecord.setContentType(contentType);
				filesRecord.setSort(0);
				filesRecord.setStatus(Const.FILES_STATUS_INIT);
				filesRecord.setCreateTime(now);
				// 插入图片并得到Files.id
				retail.setImgOne(filesService.insertAndReturnPK(filesRecord));
			}

			// 图片2
			if (!imgTwoFile.isEmpty()) {
				fileName = imgTwoFile.getOriginalFilename();
				ext = fileName.substring(fileName.lastIndexOf('.') + 1);
				newFileName = UUID.randomUUID().toString() + "." + ext;
				size = (int) imgTwoFile.getSize();
				contentType = imgTwoFile.getContentType();
				File targetFile = new File(path, newFileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				imgTwoFile.transferTo(targetFile);

				filesRecord = new Files();
				// 删除历史图片
				if (retail.getImgTwo() != null) {
					filesRecord.setId(retail.getImgTwo());
					filesRecord.setStatus(Const.FILES_STATUS_DELETE);
					filesService.updateById(filesRecord);
				}

				filesRecord.setPath(Const.UPLOAD_PATH_RETAIL + newFileName);
				filesRecord.setType(type);
				filesRecord.setName(fileName);
				filesRecord.setExt(ext);
				filesRecord.setSize(size);
				filesRecord.setContentType(contentType);
				filesRecord.setSort(0);
				filesRecord.setStatus(Const.FILES_STATUS_INIT);
				filesRecord.setCreateTime(now);
				// 插入图片并得到Files.id
				retail.setImgTwo(filesService.insertAndReturnPK(filesRecord));
			}

			// 图片3
			if (!imgThreeFile.isEmpty()) {
				fileName = imgThreeFile.getOriginalFilename();
				ext = fileName.substring(fileName.lastIndexOf('.') + 1);
				newFileName = UUID.randomUUID().toString() + "." + ext;
				size = (int) imgThreeFile.getSize();
				contentType = imgThreeFile.getContentType();
				File targetFile = new File(path, newFileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				imgThreeFile.transferTo(targetFile);

				filesRecord = new Files();
				// 删除历史图片
				if (retail.getImgThree() != null) {
					filesRecord.setId(retail.getImgThree());
					filesRecord.setStatus(Const.FILES_STATUS_DELETE);
					filesService.updateById(filesRecord);
				}

				filesRecord.setPath(Const.UPLOAD_PATH_RETAIL + newFileName);
				filesRecord.setType(type);
				filesRecord.setName(fileName);
				filesRecord.setExt(ext);
				filesRecord.setSize(size);
				filesRecord.setContentType(contentType);
				filesRecord.setSort(0);
				filesRecord.setStatus(Const.FILES_STATUS_INIT);
				filesRecord.setCreateTime(now);
				// 插入图片并得到Files.id
				retail.setImgThree(filesService.insertAndReturnPK(filesRecord));
			}

			String message = ValidatorUtils.validate(retail);
			if (StringUtils.isBlank(message)) {
				if (retail.getId() != 0) {
					retail.setUpdateTime(now);
					retailService.updateById(retail);
				} else {
					retail.setCreateTime(now);
					retail.setUpdateTime(now);
					retail.setId(retailService.insertAndReturnPK(retail));
				}

				WebContext.setAttribute(Const.MSG, "保存成功");
				WebContext.setAttribute("retailRegion", dictService.selectByColumn(Const.RETAIL_REGION));
				WebContext.setAttribute("retailArea", retailAreaService.selectAreaByRegion(retail.getRegion(), Const.STATUS_ENABLED));
				if (retail.getImgOne() != null) {
					WebContext.setAttribute("imgOnePath", FileUtil.getUrl(filesService.selectById(retail.getImgOne())));
				}
				if (retail.getImgTwo() != null) {
					WebContext.setAttribute("imgTwoPath", FileUtil.getUrl(filesService.selectById(retail.getImgTwo())));
				}
				if (retail.getImgThree() != null) {
					WebContext.setAttribute("imgThreePath", FileUtil.getUrl(filesService.selectById(retail.getImgThree())));
				}
			} else {
				WebContext.setAttribute(Const.MSG, message);
			}
		} catch (Exception e) {
			logger.error("保存失败", e);
			WebContext.setAttribute(Const.MSG, "保存失败");
		}
		return "/front/retailAdd";
	}

	/**
	 * 删除授权门市
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(@RequestParam Integer id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(Const.STATUS, -1);
		Retail record = retailService.selectById(id);
		if (record == null) {
			map.put(Const.MSG, "未查到授权门市信息");
			return map;
		}

		List<Integer> filesIds = new ArrayList<Integer>();
		if (record.getImgOne() != null) {
			filesIds.add(record.getImgOne());
		}
		if (record.getImgTwo() != null) {
			filesIds.add(record.getImgTwo());
		}
		if (record.getImgThree() != null) {
			filesIds.add(record.getImgThree());
		}

		// 删除授权门市上传文件
		if (!filesIds.isEmpty()) {
			filesService.updateStatusByIds(filesIds, Const.FILES_STATUS_DELETE);
		}
		// 删除授权门市
		retailService.deleteById(id);
		map.put(Const.STATUS, 0);
		return map;
	}

	/**
	 * 删除图片
	 * 
	 * @param id
	 * @param type
	 * @return
	 */
	@RequestMapping("/deleteImg")
	@ResponseBody
	public Object deleteImg(@RequestParam Integer id, @RequestParam Integer fileId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(Const.STATUS, -1);
		if (id == null || fileId == null) {
			map.put(Const.MSG, "参数异常");
			return map;
		}
		Retail record = retailService.selectById(id);
		if (record == null) {
			map.put(Const.MSG, "未查到门店信息");
			return map;
		}
		if (fileId.equals(record.getImgTwo())) {
			record.setImgTwo(null);
		} else if (fileId.equals(record.getImgThree())) {
			record.setImgThree(null);
		} else {
			map.put(Const.MSG, "删除失败,fileId不存在");
			return map;
		}
		record.setUpdateTime(new Date());
		int i = retailService.update(record);
		if (i > 0) {
			filesService.updateStatusByIds(Arrays.asList(fileId), Const.FILES_STATUS_DELETE);// 删除轮播图
			map.put(Const.STATUS, 0);
		} else {
			map.put(Const.MSG, "删除失败");
		}
		return map;
	}
}
